package controllers;

import java.util.List;

import com.google.gson.reflect.TypeToken;

import controllers.Security;
import models.Comment;
import models.Course;
import models.Lecture;
import models.Question;
import models.User;
import models.serializer.*;
import play.data.validation.Required;
import play.libs.F.IndexedEvent;
import play.mvc.*;

@With(Secure.class)
public class Lectures extends Controller {

    public static void show(Long lectureId) {
    	Lecture lecture = Lecture.findById(lectureId);
    	User user = Security.getConnected();
    	notFoundIfNull(lecture);
        render(lecture, user);
    }
    
    public static void addComment(Long lectureId, @Required String content) {
    	Lecture lecture = Lecture.findById(lectureId);
    	User user = Security.getConnected();
    	lecture.comment(user, content);
    	show(lectureId);
    }
    
    public static void deleteComment(Long lectureId, Long commentId) {
    	User user = Security.getConnected();
    	Comment comment = Comment.findById(commentId);
    	
    	if (comment.postedBy == user || user.isAdmin)
    		comment.delete();
    	show(lectureId);
    }
    
    public static void addQuestion(@Required Long lectureId, @Required String title, @Required String content) {
    	User user = Security.getConnected();
    	Lecture lecture = Lecture.findById(lectureId);
    	if (Security.connectedUserIsPremium()) {
    		Question question = new Question(user, lecture, title, content);
    		Questions.show(question.id);
    	}
    	show(lectureId);
    }
    
    public static void getNewComments(long lectureId, long commentId) {
    	Lecture lecture = Lecture.findById(lectureId);
    	List<Comment> newComments = Comment.find("lecture = ? and id > ?", lecture, commentId).fetch();
    	renderJSON(newComments, CommentJsonSerializer.get(), UserJsonSerializer.get());
    }

}
